﻿using dotless.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

namespace lxwmvc
{
    /// <summary>
    /// 全局拦截请求
    /// </summary>
    public class lxwHandleFactory : PageHandlerFactory, IReadOnlySessionState
    {
        /// <summary>
        /// 拦截所有请求
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requestType"></param>
        /// <param name="virtualPath"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
        {
            var not = false;
            context.Items["_controller_"] = "_defaultcontroller_";
            context.Items["_action_"] = "_defaultaction_";
            //给velocity准备
            context.Items["_area_"] = "_defaultarea_";

            string[] inputs = context.Request.Url.AbsolutePath.Substring(1).Split('/');
            while (true)
            {
                var count = inputs.Length;
                if (inputs[count - 1].Contains("."))
                {
                    not = true;
                    break;
                }
                if (inputs.Length > 0 && inputs[count - 1].Trim() != "")
                {
                    var action = inputs[count - 1].Trim();
                    context.Items["_action_"] = action.ToLower();
                    if (action.Contains("!"))
                    {
                        var arr = action.Split('!');
                        context.Items["_action_"] = arr[0].ToLower();
                        var newarr = arr.ToList();
                        newarr.RemoveAt(0);

                        context.Items["_arg_"] = newarr.ToArray();
                    }

                }


                if (inputs.Length > 1 && inputs[count - 2].Trim() != "")
                    context.Items["_controller_"] = inputs[count - 2].ToLower().Trim();

                if (inputs.Length > 2 && inputs[count - 3].Trim() != "")
                    context.Items["_area_"] = inputs[count - 3].ToLower().Trim();

                //处理特殊请求
                {
                    if (context.Items["_controller_"].tostr() == "artist"
                        || context.Items["_controller_"].tostr() == "detail"
                        || context.Items["_controller_"].tostr() == "arts"
                        || context.Items["_controller_"].tostr() == "bgimage" 
                        )
                    {
                        //前面多加一个0
                        if (!context.Items["_action_"].tostr().StartsWith("0"))
                        {
                            context.Items["_controller_"] = "_defaultcontroller_";
                            break;
                        }

                        var newarr = new List<string>();
                        newarr.Add(inputs[count - 1]+ "");
                        context.Items["_action_"] = context.Items["_controller_"];
                        context.Items["_controller_"] = "_defaultcontroller_";

                        context.Items["_arg_"] = newarr.ToArray();
                    }
                }

                not = false;
                break;
            }

            if (!not)
            {
                try
                {
                    return new lxwHandler();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            else
            {
                var input = context.Request.Url.AbsolutePath.ToLower().Trim();
                //这里config cs，是不能通过的
                if (input.EndsWith(".config")|| input.EndsWith(".cs")|| input.EndsWith(".dll"))
                    return null;

                if (input.EndsWith(".aspx"))
                    return base.GetHandler(context, requestType, virtualPath, path);

                if (input.EndsWith(".ashx"))
                    return base.GetHandler(context, requestType, virtualPath, path);

                if (input.EndsWith(".less"))
                    return new LessCssHttpHandler();

                

                return new DefaultHttpHandler();
                //return base.GetHandler(context, requestType, virtualPath, path);
            }
        }
    }


    /// <summary>
    /// 拦截请求并处理
    /// </summary>
    public class lxwHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 执行请求
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            using(pagebase pb = new pagebase())
            {
                pb.execute(context);
            }
        }

        /// <summary>
        /// 不保存状态
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    //public class lessHandler : IHttpHandler
    //{
    //    /// <summary>
    //    /// 执行请求
    //    /// </summary>
    //    /// <param name="context"></param>
    //    public void ProcessRequest(HttpContext context)
    //    {
    //        try
    //        {
    //            var source = "";
    //            var filename = "";
    //            Ruleset ruleset = new dotless.Core.Parser.Parser().Parse(source, fileName);
    //            var rv = ruleset.ToCSS(new dotless.Core.Parser.Infrastructure.Env()
    //            {
    //                Compress = true
    //            });
    //            // <dotless minifyCss="false" cache="true" web="false" strictMath="false"/>
    //        }
    //        catch (ParserException pe)
    //        {
                
    //        }
    //    }

    //    /// <summary>
    //    /// 不保存状态
    //    /// </summary>
    //    public bool IsReusable
    //    {
    //        get
    //        {
    //            return false;
    //        }
    //    }
    //}
}